package com.hu.jie.mynoteedit;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.EditText;

/**
 * Created by jie on 2016/6/29.
 */
public class NoteEdit extends EditText{
    private int lineColor = Color.BLACK;
    private float lineWidth = 1;
    private int paddingLeft = 20;
    private int paddingRight = 20;
    private Paint paint;

    public NoteEdit(Context context) {
        super(context);
    }

    public NoteEdit(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NoteEdit);
        lineColor = typedArray.getColor(R.styleable.NoteEdit_line_color,lineColor);
        lineWidth = typedArray.getDimension(R.styleable.NoteEdit_line_width,lineWidth);

        paddingLeft = typedArray.getDimensionPixelOffset(R.styleable.NoteEdit_line_paddingLeft,paddingLeft);
        paddingRight = typedArray.getDimensionPixelOffset(R.styleable.NoteEdit_line_padddingRight,paddingRight);
        //需要回收，一定是在解析之后才能回收
        typedArray.recycle();

        paint = new Paint();
        paint.setColor(lineColor);
        paint.setStrokeWidth(lineWidth);

        //设置内边距的方法
        setPadding(paddingLeft,0,paddingRight,0);//左上右下
        //调整默认光标位置
        setGravity(Gravity.START);

        setBackgroundColor(Color.TRANSPARENT);//透明色
    }

    public NoteEdit(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    /**
     * 画线--到底画多条线？(整个View的高度，和光标所在每一行的高度，可以计算出)
     * 线的位置应该怎么定
     * 补线(比showLineCount多出的行数都需要补线)
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int viewHeight = getHeight();
        int lineHeight = getLineHeight();
        int showLineCount = viewHeight / lineHeight ;
        for (int i = 0; i < showLineCount; i++) {
            canvas.drawLine(paddingLeft,lineHeight *(i+1),getWidth()-paddingRight,lineHeight*(i+1),paint);
        }
        //超出屏幕，要继续补上新的下划线
        //当前所在的行数 - 已经绘制的行数
        //当extraLineCount>0的时候开始补线，因为<0在showLineCount范围内的线都划过了
        int extraLineCount = getLineCount() - showLineCount;
        if(extraLineCount >0){
            //添加新的线
            for (int i = showLineCount; i < getLineCount(); i++) {
                canvas.drawLine(paddingLeft,lineHeight *(i+1),getWidth()-paddingRight,lineHeight*(i+1),paint);
            }
        }
    }
}
